import React, { useState, useRef } from 'react';
import {
  ModalSheet,
  ModalSheetHeader,
  ModalSheetBody,
  ModalSheetFooter,
} from '../../components/common/ModalSheet';
import type {
  ModalSheetSize,
  ModalSheetPosition,
  ModalSheetAnimation,
  ModalSheetRef,
  SnapPoint,
} from '../../components/common/ModalSheet';
import './ModalSheetDemo.css';

/**
 * Modal Sheet 演示页面
 */
export const ModalSheetDemo: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [size, setSize] = useState<ModalSheetSize>('medium');
  const [position, setPosition] = useState<ModalSheetPosition>('bottom');
  const [animation, setAnimation] = useState<ModalSheetAnimation>('slide');
  const [draggable, setDraggable] = useState(true);
  const [resizable, setResizable] = useState(false);

  // Snap Points 相关状态
  const [useSnapPoints, setUseSnapPoints] = useState(false);
  const [snapPoints] = useState<SnapPoint[]>([0, 320, 0.5, -100, 1]);
  const [currentSnap, setCurrentSnap] = useState(1); // 与 initialSnap 保持一致
  const modalRef = useRef<ModalSheetRef>(null);

  const openModal = () => {
    // 功能组合验证
    if (useSnapPoints && !draggable) {
      console.warn('⚠️ Snap Points 模式建议启用拖拽功能以获得最佳体验');
    }
    setIsOpen(true);
  };

  const closeModal = () => setIsOpen(false);

  // Snap Points 控制方法
  const handleSnapTo = (index: number) => {
    modalRef.current?.snapTo(index);
  };

  const handleSnapChange = (snapIndex: number, snapValue: SnapPoint) => {
    setCurrentSnap(snapIndex);
    console.log(`Snapped to index ${snapIndex}, value: ${snapValue}`);
  };

  return (
    <div className='modal-sheet-demo'>
      <div className='demo-header'>
        <h1>Modal Sheet 组件演示</h1>
        <p>一个功能完整、高度可定制的 Modal Sheet 组件</p>
      </div>

      <div className='demo-controls'>
        <div className='control-group'>
          <label>尺寸:</label>
          <select
            value={size}
            onChange={e => setSize(e.target.value as ModalSheetSize)}
          >
            <option value='small'>Small</option>
            <option value='medium'>Medium</option>
            <option value='large'>Large</option>
            <option value='full'>Full</option>
            <option value='auto'>Auto</option>
          </select>
        </div>

        <div className='control-group'>
          <label>位置:</label>
          <select
            value={position}
            onChange={e => setPosition(e.target.value as ModalSheetPosition)}
          >
            <option value='bottom'>Bottom</option>
            <option value='top'>Top</option>
            <option value='left'>Left</option>
            <option value='right'>Right</option>
          </select>
        </div>

        <div className='control-group'>
          <label>动画:</label>
          <select
            value={animation}
            onChange={e => setAnimation(e.target.value as ModalSheetAnimation)}
          >
            <option value='slide'>Slide</option>
            <option value='fade'>Fade</option>
            <option value='scale'>Scale</option>
            <option value='none'>None</option>
          </select>
        </div>

        <div className='control-group'>
          <label>
            <input
              type='checkbox'
              checked={draggable}
              onChange={e => setDraggable(e.target.checked)}
            />
            可拖拽
          </label>
        </div>

        <div className='control-group'>
          <label>
            <input
              type='checkbox'
              checked={resizable}
              onChange={e => setResizable(e.target.checked)}
            />
            可调整大小
          </label>
        </div>

        <div className='control-item'>
          <label>
            <input
              type='checkbox'
              checked={useSnapPoints}
              onChange={e => setUseSnapPoints(e.target.checked)}
            />
            启用 Snap Points
          </label>
        </div>
      </div>

      {useSnapPoints && (
        <div className='control-group'>
          <h3>Snap Points 控制</h3>
          <div className='snap-points-info'>
            <p>
              当前 Snap Point: {currentSnap} (值: {snapPoints[currentSnap]})
            </p>
            <p>
              说明: 0=关闭, 0-1=百分比, 负数=距顶部像素, 1=全屏, 其他=具体像素
              (320px适合左右弹出)
            </p>
          </div>
          <div className='snap-controls'>
            {snapPoints.map((point, index) => (
              <button
                key={index}
                className={`snap-button ${currentSnap === index ? 'active' : ''} ${!isOpen ? 'disabled' : ''}`}
                onClick={() => handleSnapTo(index)}
                disabled={!isOpen}
                title={
                  !isOpen ? '请先打开 Modal 后使用' : `跳转到吸附点 ${index}`
                }
              >
                {index}:{' '}
                {point === 0
                  ? '关闭'
                  : point === 1
                    ? '全屏'
                    : point > 0 && point < 1
                      ? `${Math.round(point * 100)}%`
                      : point < 0
                        ? `距顶${Math.abs(point)}px`
                        : `${point}px`}
              </button>
            ))}
          </div>
        </div>
      )}

      <div className='demo-actions'>
        <button className='demo-button primary' onClick={openModal}>
          打开 Modal Sheet
        </button>
      </div>

      <div className='demo-features'>
        <h2>组件特性</h2>
        <div className='features-grid'>
          <div className='feature-card'>
            <h3>🎨 多种样式</h3>
            <p>支持 5 种尺寸、4 种位置、4 种动画效果</p>
          </div>
          <div className='feature-card'>
            <h3>🖱️ 交互丰富</h3>
            <p>支持拖拽移动、大小调整、键盘操作</p>
          </div>
          <div className='feature-card'>
            <h3>♿ 无障碍</h3>
            <p>完整的 ARIA 支持、焦点管理、键盘导航</p>
          </div>
          <div className='feature-card'>
            <h3>📱 响应式</h3>
            <p>移动端友好，自适应不同屏幕尺寸</p>
          </div>
          <div className='feature-card'>
            <h3>🎭 主题支持</h3>
            <p>支持亮色/暗色主题，可自定义样式</p>
          </div>
          <div className='feature-card'>
            <h3>⚡ 高性能</h3>
            <p>Portal 渲染、动画优化、内存管理</p>
          </div>
        </div>
      </div>

      <div className='demo-usage'>
        <h2>使用示例</h2>
        <pre className='code-block'>
          {`import { 
  ModalSheet, 
  ModalSheetHeader, 
  ModalSheetBody, 
  ModalSheetFooter 
} from '@/components/common/ModalSheet';

function MyComponent() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <button onClick={() => setIsOpen(true)}>
        打开 Modal
      </button>
      
      <ModalSheet
        open={isOpen}
        onClose={() => setIsOpen(false)}
        size="medium"
        position="bottom"
        animation="slide"
        draggable
        resizable
      >
        <ModalSheetHeader title="标题" />
        <ModalSheetBody>
          <p>这里是内容区域</p>
        </ModalSheetBody>
        <ModalSheetFooter>
          <button onClick={() => setIsOpen(false)}>
            关闭
          </button>
        </ModalSheetFooter>
      </ModalSheet>
    </>
  );
}`}
        </pre>
      </div>

      {/* Modal Sheet 实例 */}
      <ModalSheet
        ref={modalRef}
        open={isOpen}
        onClose={closeModal}
        size={useSnapPoints ? undefined : size}
        position={position}
        animation={animation}
        draggable={draggable} // Snap Points 模式下也支持拖拽调整
        resizable={resizable} // 可调整大小功能可以与Snap Points共存
        snapPoints={useSnapPoints ? snapPoints : undefined}
        initialSnap={useSnapPoints ? 1 : undefined}
        onSnap={useSnapPoints ? handleSnapChange : undefined}
        onBeforeOpen={() => console.log('Modal 即将打开')}
        onAfterOpen={() => console.log('Modal 已打开')}
        onBeforeClose={() => console.log('Modal 即将关闭')}
        onAfterClose={() => console.log('Modal 已关闭')}
        onDragStart={() => {
          console.log('🚀 开始拖拽');
          console.log('💡 提示：拖拽整个弹框来移动它的位置');
        }}
        onDrag={(_, position) => {
          console.log('🖱️ 拖拽中:', `x: ${position.x}px, y: ${position.y}px`);
        }}
        onDragEnd={(_, position) => {
          console.log(
            '✅ 拖拽结束:',
            `最终位置 x: ${position.x}px, y: ${position.y}px`
          );
        }}
      >
        <ModalSheetHeader title='Modal Sheet 演示' />
        <ModalSheetBody>
          <div className='modal-content'>
            <h3>欢迎使用 Modal Sheet 组件！</h3>
            <p>这是一个功能完整的 Modal Sheet 组件，具有以下特性：</p>
            <ul>
              <li>✅ 多种尺寸和位置选择</li>
              <li>✅ 丰富的动画效果 (Framer Motion)</li>
              <li>✅ 拖拽和调整大小功能</li>
              <li>🆕 Snap Points 吸附点系统</li>
              <li>🆕 增强的手势识别</li>
              <li>🆕 Ref 控制方法</li>
              <li>✅ 完整的键盘支持</li>
              <li>✅ 无障碍访问支持</li>
              <li>✅ 响应式设计</li>
              <li>✅ TypeScript 类型支持</li>
            </ul>

            {draggable && (
              <div
                style={{
                  padding: '12px',
                  backgroundColor: '#e3f2fd',
                  borderRadius: '8px',
                  marginTop: '16px',
                  border: '1px solid #2196f3',
                }}
              >
                <h4 style={{ margin: '0 0 8px 0', color: '#1976d2' }}>
                  🖱️ 拖拽功能已启用 {useSnapPoints && '(Snap Points 模式)'}
                </h4>
                <p style={{ margin: 0, fontSize: '14px', color: '#555' }}>
                  {useSnapPoints
                    ? '在拖拽条上拖动可以调整到不同的吸附点位置'
                    : position === 'left' || position === 'right'
                      ? `在${position === 'left' ? '右侧' : '左侧'}边缘找到拖拽条，点击并拖动即可移动整个弹框`
                      : `在${position === 'top' ? '底部' : '顶部'}找到拖拽条（横条），点击并拖动即可移动整个弹框`}
                </p>
                <p
                  style={{
                    margin: '4px 0 0 0',
                    fontSize: '12px',
                    color: '#666',
                  }}
                >
                  💡 拖拽条hover时会有背景色变化。查看控制台了解拖拽事件详情。
                </p>
                <div
                  style={{
                    marginTop: '8px',
                    padding: '8px',
                    backgroundColor: '#fff3e0',
                    borderRadius: '4px',
                    border: '1px solid #ff9800',
                  }}
                >
                  <p
                    style={{
                      margin: 0,
                      fontSize: '12px',
                      color: '#e65100',
                      fontWeight: 'bold',
                    }}
                  >
                    🎯 试试看：点击并拖动拖拽条来移动弹框到任意位置！
                  </p>
                </div>
              </div>
            )}

            {useSnapPoints && (
              <div className='snap-demo-info'>
                <h4>🎯 Snap Points 演示</h4>
                <p>当前模式：Snap Points 吸附点系统</p>
                <p>你可以：</p>
                <ul>
                  <li>拖拽顶部的拖拽条来调整高度</li>
                  <li>使用上方的按钮快速跳转到指定位置</li>
                  <li>松手时会自动吸附到最近的点</li>
                </ul>
              </div>
            )}

            <div className='demo-form'>
              <h4>表单示例</h4>
              <div className='form-group'>
                <label htmlFor='name'>姓名:</label>
                <input type='text' id='name' placeholder='请输入姓名' />
              </div>
              <div className='form-group'>
                <label htmlFor='email'>邮箱:</label>
                <input type='email' id='email' placeholder='请输入邮箱' />
              </div>
              <div className='form-group'>
                <label htmlFor='message'>消息:</label>
                <textarea
                  id='message'
                  rows={4}
                  placeholder='请输入消息内容'
                ></textarea>
              </div>
            </div>
          </div>
        </ModalSheetBody>
        <ModalSheetFooter align='space-between'>
          <button className='demo-button secondary' onClick={closeModal}>
            取消
          </button>
          <div>
            <button
              className='demo-button secondary'
              style={{ marginRight: '8px' }}
            >
              重置
            </button>
            <button className='demo-button primary' onClick={closeModal}>
              确认
            </button>
          </div>
        </ModalSheetFooter>
      </ModalSheet>
    </div>
  );
};

export default ModalSheetDemo;
